<?php
$appid = 'wxe6cc8a136b6aca40';
$secret = '990351bb02c512d488bcf46aa73c9ffe';
$token = 'duans';

/*
获取时间:20-22 15:49

{"access_token":"14_rLvCHG5_AYLMWwm48Rd13OwkfxR6W-K_bqLSY-rMD9u8d2FlMImDSJeFRx-PrS7WAx9f5YwlKLIf0pTIbkioie2cK_BLOj4fPmrjVBgACKYUhrWge41Kn_Ribxn859oU7tsjbjuiy_Uir2ieCTGfAEAQHU","expires_in":7200}

 */

//获取微信服务器IP
// get_wx_server_ip();
function get_wx_server_ip()
{
    $access_token = get_access_token();
    $url = 'https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=' . $access_token;
    $ret = curl($url);
    // file_put_contents('wx_server_ip_list.json', $ret);
    // echo '获取微信服务器IP列表ok';
    return $ret;
}

//获取微信access_token
// get_access_token();
function get_access_token()
{
    $is_valid = false;
    if (file_exists('access_token.json')) {
        $access_token = file_get_contents('access_token.json');
        if (!empty($access_token)) {

            $access_token = json_decode($access_token, true);

            if (is_array($access_token) && $access_token['expires'] > time() + 7100) {
                $is_valid = true;
                return $access_token['access_token'];
            }
        }
    }

    if (!$is_valid) {
        global $appid;
        global $secret;
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $secret;
        $ret = json_decode(curl($url), true);
        $arr = array('access_token' => $ret['access_token'], 'expires' => time() + 7100);
        file_put_contents('access_token.json', json_encode($arr));
        return $ret['access_token'];
    }

}

/*
验证消息是否来自微信服务器
 */
function checkSignature()
{
    $signature = $_GET["signature"];
    $timestamp = $_GET["timestamp"];
    $nonce = $_GET["nonce"];
    global $token;

    //公众平台设置开发者服务器url地址的时候,微信服务器会发送此参数
    $echostr = $_GET['echostr'];

    $tmpArr = array($token, $timestamp, $nonce);
    sort($tmpArr, SORT_STRING);
    $tmpStr = implode($tmpArr);
    $tmpStr = sha1($tmpStr);

    if ($tmpStr == $signature) {
        return true;
    } else {
        return false;
    }
}

/*
图灵聊天机器人
参数格式:
{
"reqType":0,
"perception": {
"inputText": {
"text": "附近的酒店"
},
"inputImage": {
"url": "imageUrl"
},
"selfInfo": {
"location": {
"city": "北京",
"province": "北京",
"street": "信息路"
}
}
},
"userInfo": {
"apiKey": "",
"userId": ""
}
}

返回值格式(实测)
{"emotion":{"robotEmotion":{"a":0,"d":0,"emotionId":33000,"p":0},"userEmotion":{"a":0,"d":0,"emotionId":10300,"p":0}},"intent":{"actionName":"","code":10004,"intentName":""},"results":[{"groupType":1,"resultType":"text","values":{"text":"我拒绝交谈，哼！"}}]}
 */
function tl_chat($msg)
{
    $param = array(
        'reqType' => 0,
        'perception' => array(
            'inputText' => array(
                'text' => $msg,
            )
        ),
        'userInfo' => array(
            'apiKey' => '94bcd348d35d4025a456dde81fd4826b',
            'userId' => 'itheimaweb12', //120a59b240d33401
        ),
    );
    $url = 'http://openapi.tuling123.com/openapi/api/v2';
    $ret = curl($url, json_encode($param, JSON_UNESCAPED_UNICODE));
    $arr_ret = json_decode($ret, true);
    // file_put_contents('log/tl.json',$ret);
    if ($arr_ret['intent']['code'] != 5000) {
        $msg_response = $arr_ret['results'][0]['values']['text'];
    } else {
        $msg_response = '图灵机器人异常';
    }
    return $msg_response;
}

/*
青云客智能聊天机器人API
接口返回数组格式:
{
result: 0,
content: "{face:14}Hello~"
}
 */
function free_chat($msg)
{
    $url = 'http://api.qingyunke.com/api.php?key=free&appid=0&msg=' . $msg;
    $ret = curl($url);
    $json = json_decode($ret, true);
    return $json['content'];

}

/*
将xml数据转换成数组
参数:xml字符串
 */
/*
<xml><ToUserName><![CDATA[gh_5412f4d789f3]]></ToUserName>
<FromUserName><![CDATA[o4Nu3jvnWkCbOYVnpiILneOfTycM]]></FromUserName>
<CreateTime>1540196729</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[ceshi ]]></Content>
<MsgId>6615094581262291268</MsgId>
</xml>
 */
function xml2array($xml)
{
    //从xml中解析出php对象
    $obj = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
    //将对象转换成json
    $json = json_encode($obj);
    //将json转换成数组
    $arr = json_decode($json, true);
    return $arr;
}
/*
将数组转化成xml
参数:数组
 */
function array2xml($arr)
{
    $xml = "<xml>";
    foreach ($arr as $key => $val) {
        if (is_numeric($val)) {
            $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
        } else {
            $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
        }
    }
    $xml .= "</xml>";
    return $xml;
}
//发送curl请求
function curl($url, $posts = "")
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, $posts ? 0 : 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $posts);
    $ret = curl_exec($ch);
    curl_close($ch);
    return $ret;

}
